import { IpcInvokeError } from "@/framework/ipc/ipc-invoke-error";
import type { IpcServiceResponse } from "@common/ipc-service-types";

/**
 * 调用主进程 IPC Service
 * @param channel
 * @param args
 */
export function invokeService(channel: string, ...args: any[]) {
  return new Promise<any>((resolve, reject) => {
    ipc
      .invoke(`ipc://${channel}`, ...args)
      .then((resp: IpcServiceResponse) => {
        if (resp.error) {
          reject(new IpcInvokeError(resp.error));
          return;
        }
        resolve(resp.data);
      })
      .catch(e => {
        if (!e) {
          reject(new IpcInvokeError("Invoke IPC Error"));
          return;
        }
        if (typeof e === "string") {
          reject(new IpcInvokeError(e));
          return;
        }

        reject(new IpcInvokeError(e.message));
      });
  });
}
